package com.gitee.yangtianle.redisson.seckill.spring.boot.autoautoconfigure.config;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;

/**
 * @author tianle.ytl
 * @date 2018/9/19
 */
@Configuration
@ConditionalOnClass(Config.class)
public class RedissonAutoConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(RedissonAutoConfiguration.class);

    @Autowired
    private Environment environment;

    @Bean(destroyMethod = "shutdown")
    public RedissonClient initRedissonClient() {
        String profile = "";
        String[] activeProfiles = environment.getActiveProfiles();
        if (activeProfiles.length != 0) {
            profile = "-" + activeProfiles[0];
        }
        String url = "redisson" + profile + ".yml";
        RedissonClient redissonClient = null;
        try {
            Config config = Config.fromYAML(new ClassPathResource(url).getInputStream());
            redissonClient = Redisson.create(config);
            logger.info("The redisson configuration file was loaded successfully. url = {}", url);
        } catch (IOException e) {
            logger.error("Redisson configuration file not found or The configuration is error. url = {]",url);
            e.printStackTrace();
        }
        return redissonClient;
    }

//    try {
//        File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX);
//    } catch (FileNotFoundException e) {
//        e.printStackTrace();
//    }
}
